package com.lemon.funplus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.audiofx.AcousticEchoCanceler;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lemon.funplus.object.AccountObject;
import com.lemon.funplus.parse.JsonParser;
import com.lemon.funplus.parse.UploadParse;
import com.lemon.funplus.ulti.AppUtils;
import com.lemon.funplus.ulti.BaseEngine;

public class UploadActivity extends Activity {

	EditText edtTitle;
	ImageView imageView;
	TextView txtAvatarPath;
	UploadParse jsonParser;
	AccountObject accountObject;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.upload_layout);

		initView();
		jsonParser = new UploadParse();
	}

	void initView() {
		edtTitle = (EditText) findViewById(R.id.editText_title);
		imageView = (ImageView) findViewById(R.id.imageView_show);
		txtAvatarPath = (TextView) findViewById(R.id.textView_path);
		imageView.setOnClickListener(clickListener);
		(findViewById(R.id.actionbar_imageDrawer)).setOnClickListener(clickListener);
		(findViewById(R.id.button_upload_image)).setOnClickListener(clickListener);
	}

	OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.imageView_show:
				chooseImage();
				break;
			case R.id.actionbar_imageDrawer:
				onBackPressed();
				break;
			case R.id.button_upload_image:
				upload();
				break;
			default:
				break;
			}
		}
	};
	String sImage = "";

	void upload() {
		if (!edtTitle.getText().toString().equals("")) {
			if (bitmap != null) {
				sImage = BaseEngine.BitmapTobase64(bitmap);
				new upload().execute("");
			} else
				Toast.makeText(UploadActivity.this, "Ảnh không hợp lệ!", Toast.LENGTH_SHORT).show();
		} else
			Toast.makeText(UploadActivity.this, "Tiêu đề không được để trống!", Toast.LENGTH_SHORT).show();
	}

	private static final int SELECT_PICTURE = 1;
	String imagePath = "";
	Bitmap bitmap;

	public void chooseImage() {
		accountObject=AppUtils.getAccount(UploadActivity.this);
		if (accountObject!=null && accountObject.getname()!=null) {
			Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(i, SELECT_PICTURE);
		}else{
			Intent intent=new Intent(UploadActivity.this, AccountLoginActivity.class);
			startActivity(intent);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case SELECT_PICTURE:

			if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK && null != data) {
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
				cursor.moveToFirst();

				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				cursor.close();
				bitmap = BitmapFactory.decodeFile(picturePath);
				if (bitmap != null) {
					txtAvatarPath.setText(imagePath);
					imageView.setImageBitmap(bitmap);
				}

			}
			break;
		}
	}

	class upload extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String str = "";
			try {
				BaseEngine.showLogformLongString("sImage:", sImage);
				writeToFile("base64", sImage);
				List<NameValuePair> param = new ArrayList<NameValuePair>();
				param.add(new BasicNameValuePair("type", "picture"));
				param.add(new BasicNameValuePair("title", edtTitle.getText().toString()));
				param.add(new BasicNameValuePair("uname", accountObject.getname()));
				param.add(new BasicNameValuePair("image", sImage));
				str = jsonParser.m_HTTPrequet("http://funplus.vn/incoming.ssl?act=upimage", "POST", param);
				// BaseEngine.showLogformLongString("upload", str);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			if (result != null) {
//				BaseEngine.showLogformLongString("upload", result);
				try {
					ArrayList<String> str = JsonParser.readStatus(result);
					Log.i("", str.get(0));
					Log.i("", str.get(1));
					Toast.makeText(UploadActivity.this, str.get(1), Toast.LENGTH_SHORT).show();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void writeToFile(String fileName, String body) {
		FileOutputStream fos = null;

		try {
			final File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/funplus/");

			if (!dir.exists()) {
				dir.mkdirs();
			}

			final File myFile = new File(dir, fileName + ".txt");

			if (!myFile.exists()) {
				myFile.createNewFile();
			}

			fos = new FileOutputStream(myFile);

			fos.write(body.getBytes());
			fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
